<style lang="scss" scoped>
@import "@/assets/css/variable";
.applyForm {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: $main-bgc;
  min-height: 100%;
  overflow: auto;
  box-sizing: border-box;
  padding: 1.6rem;
  .box1 {
    background-color: white;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .line {
      font-size: 1.2rem;
      display: flex;
      align-items: center;
      span {
        flex: 1;
      }
      // .pheone {
      //   display: flex;
      //   align-items: center;
      // }
    }
  }
  .box2 {
    background-color: white;
    .line {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
    }
    .title {
      font-size: 1.4rem;
      font-weight: bold;
    }
  }
}
</style>
<template>
  <div class="applyForm">
    <div class="box1 padding-all-m border-r-l" v-if="item">
      <div class="title title-l">{{ item.title }}</div>
      <div class="line margT-l">
        <span class="label color-s">商户名称</span
        ><span class="value">{{ item.merchantname }}</span>
      </div>
      <div class="line margT-l" v-show="is_plays && is_need_pay == 1">
        <span class="label color-s">发货方式</span
        ><span class="value">{{
          item.val.commodity_type == 1 ? "自提" : "发货"
        }}</span>
      </div>
      <div class="line margT-l" v-show="is_plays && is_need_pay == 1">
        <span class="label color-s">{{ val.active_title }}费用</span
        ><span class="value" :style="{ color: theme_color }"
          >{{ val.active_price || presentPrice }}元</span
        >
      </div>
      <div class="line margT-l" v-show="!is_plays && !is_need_pay">
        <span class="label color-s">发货方式</span
        ><span class="value">{{
          item.val.commodity_type == 1 ? "自提" : "发货"
        }}</span>
      </div>
      <div class="line margT-l" v-show="!is_plays && !is_need_pay">
        <span class="label color-s">{{ val.active_title }}费用</span
        ><span class="value" :style="{ color: theme_color }"
          >{{ val.active_price || presentPrice }}元</span
        >
      </div>
      <div class="line margT-l" v-show="is_plays">
        <span class="label color-s">发货方式</span
        ><span class="value">{{
          item.val.commodity_type == 1 ? "自提" : "发货"
        }}</span>
      </div>
      <div class="line margT-l" v-show="is_plays">
        <span class="label color-s">{{ val.active_title }}费用</span
        ><span class="value" :style="{ color: theme_color }"
          >{{ val.active_price || presentPrice }}元</span
        >
      </div>
      <div class="line margT-l">
        <span class="label color-s">商户电话</span>
        <span class="value pheone" style="display: flex; align-items: center"
          >{{ merchant.mobile }}
          <a :href="'tel:' + item.mobile" style="margin-left: 10px">
            <van-icon name="phone" size="1.5rem" :color="theme_color" />
          </a>
        </span>
      </div>
      <div class="line margT-l">
        <span class="label color-s">商户地址</span>
        <span class="value pheone" style="display: flex; align-items: center"
          >{{ address }}
          <van-icon
            name="location"
            size="1.5rem"
            :color="theme_color"
            @click="mapClick(address)"
          />
        </span>
      </div>
    </div>
    <div class="box2 padding-all-m border-r-l margT-l" v-if="item">
      <div>
        <span class="title">{{ val.active_title }}信息</span
        ><span class="color-s fs-12 margL-l"
          >以下均为<span :style="{ color: theme_color }">必填</span></span
        >
      </div>
      <div>
        <div class="margT-l" v-if="item.create_form">
          <k-form-build ref="kfb" :value="item.create_form" />
        </div>
      </div>
    </div>
    <div class="fix-bottom padding-lr">
      <van-button :color="theme_color" block @click="submit">提交</van-button>
    </div>
    <!-- <div style="">openId:{{openid}}</div> -->
    <!-- <div>openId2:{{openId2}}</div> -->
  </div>
</template>

<script>
import { Button, Toast, Dialog, Icon } from "vant";
// import Vue from 'vue'
import KFormDesign from "k-form-design";
// import 'k-form-design/lib/k-form-design.css';
Vue.use(KFormDesign);
// import utils from '@/assets/js/utils.js';

export default {
  name: "ApplyForm",
  components: {
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    [Icon.name]: Icon,
    KFormDesign,
  },
  data() {
    return {
      item: "",
      openid: "",
      orderItem: "",
      theme_color: "",
      val: {},
      activity_id: null,
      falg: true,
      id: null,
      staff_id: null,
      model_num: null,
      presentPrice: "",
      merchant: {},
      is_plays: null,
      is_need_pay: null,
    };
  },
  created() {
    console.log();
    this.theme_color = this.$route.hash;
    // const a = $('.fix-bottom')
    // console.log('a',a)
  },
  // computed: {
  //     getOpenId() {
  //         this.openid = this.$store.state.openid
  //         return this.openid
  //     }
  // },
  mounted() {
    const _this = this;
    _this.item = _this.$store.getters.getActivityItem;
    console.log(_this.item, "item");
    // console.log(this.item , 'this.item ');
    _this.orderItem = _this.$store.state.orderItem;
    _this.merchant = _this.$store.state.merchant;
    _this.address =
      _this.merchant.province +
      _this.merchant.city +
      _this.merchant.area +
      _this.merchant.detail_address;
    _this.theme_color = _this.$store.state.theme_color;
    _this.activity_id = _this.$route.query.activity_id;
    _this.model_num = _this.$route.query.model_num;
    console.log(_this.$route.query.is_plays, "_this.$route.query.is_plays");
    if (_this.$route.query.is_plays) {
      JSON.parse("true");
      _this.is_need_pay = 1;
      _this.is_plays = JSON.parse(_this.$route.query.is_plays);
      console.log(
        _this.is_need_pay,
        _this.is_plays,
        "_this.is_plays_this.is_plays"
      );
    }
    console.log(_this.$route, " _this.$route");
    _this.staff_id = _this.$route.query.staff_id;
    _this.presentPrice = _this.$store.state.presentPrice;
    if (_this.$route.query.presentPrice) {
      _this.presentPrice = _this.$route.query.presentPrice;
    }
    _this.id = _this.$route.query.id;
    _this.val = _this.item.val;
    if (!_this.item || !_this.orderItem) {
      _this.$router.go(-1);
    }
    if (process.env.NODE_ENV == "production") {
      _this.openid = localStorage.getItem("COPENID");
    } else {
      _this.openid = _this.$store.state.openid;
    }
    if (!_this.openid || _this.openid == "undefined") {
      _this.$router.go(-1);
    }
  },
  methods: {
    mapClick(adress) {
      this.shareInit();
      this.getLal(adress, (res) => {
        this.openLocation(
          res.detail.addressComponents.street,
          res.detail.location.lat,
          res.detail.location.lng
        );
      });
    },
    shareInit() {
      const _this = this;
      const url = location.href.split("#")[0];
      let params = {
        url: url,
      };
      _this.$request.configJssdk(params).then((res) => {
        console.log(res, "-------------res");
        wx.config({
          debug: false, // 是否开启调试模式
          appId: res.data.appId, //appid
          timestamp: res.data.timestamp, // 时间戳
          nonceStr: res.data.nonceStr, // 随机字符串
          signature: res.data.signature, // 签名
          jsApiList: ["openLocation", "getLocation"], // 需要使用的JS接口列表
        });
      });
    },
    getLal(address, cb) {
      var geocoder = new qq.maps.Geocoder();
      geocoder.getLocation(address);
      geocoder.setComplete(function (res) {
        cb(res);
      });
      geocoder.setError(function (err) {
        cb(res);
      });
    },

    openLocation(name, lat, lng) {
      wx.openLocation({
        latitude: lat,
        longitude: lng,
        name: name,
        address: this.address,
        scale: 14,
        infoUrl: "http://weixin.qq.com",
      });
    },
    submit() {
      const _this = this;
      _this.$refs.kfb
        .getData()
        .then((values) => {
          console.log("验证通过", values);
          // values.create_time = utils.formatDateYMDHM(new Date())
          // values.openid = _this.openid
          // values.is_sure = 0
          let apply_list = []; // this.orderItem.val
          apply_list.push(values);
          _this.getOrderSave(apply_list);
        })
        .catch(() => {
          console.log("验证未通过，获取失败");
        });
    },
    getOrderSave(apply_list) {
      const _this = this;
      if (_this.falg) {
        if (_this.id) {
          _this.falg = false;
          let params = {
            activity_id: _this.activity_id, // 活动ID
            val: JSON.stringify(apply_list), // 自定义表单数据
            // status: 1,// 是否打款 1否 2是
            writeoff: 1, // 是否核销 1否 2是
            // ordersn: '',// 订单编号
            // paytime: '',// 支付时间
            // transid: '',// 微信订单号
            price: _this.presentPrice, // 单价
            num: 1, // 数量
            openid: _this.openid,
            id: _this.id,
            status: 1,
            staff_id: _this.staff_id,
            // id: _this.item.id,// 修改的时候需要传
            // apply_list: apply_list
          };
          _this.$request
            .getOrderRepay(params)
            .then((res) => {
              console.log("getOrderHBTKorder", res);
              if (res.ret == 400) {
                Dialog({ message: res.msg });
                return;
              } else if (res.ret == 200) {
                let weixinParams = {
                  appId: res.data.appId, // 公众号appId，由商户传入
                  timeStamp: res.data.timeStamp, // 时间戳
                  nonceStr: res.data.nonceStr, // 随机串
                  package: res.data.package,
                  signType: res.data.signType, // 微信签名方式
                  paySign: res.data.paySign, // 微信签名
                };
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  weixinParams,
                  function (res) {
                    // Toast(res.err_msg)
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                      _this.falg = true;
                      Toast("支付成功!");
                      setTimeout(function () {
                        // _this.$router.push(
                        //   `/caseShow/${_this.item.model}/ActivityShow/${_this.activity_id}`
                        // );
                        _this.$router.go(-1);
                      }, 1500);

                      // WeixinJSBridge.call('closeWindow');
                    } else if (
                      res.err_msg == "get_brand_wcpay_request:cancel"
                    ) {
                      _this.falg = true;
                      Toast("取消支付!");
                      // WeixinJSBridge.call('closeWindow');
                    } else {
                      _this.falg = true;
                      Toast("支付失败!");
                    }
                    _this.$router.go(-1);
                    // WeixinJSBridge.call('closeWindow');
                  }
                );
              }
            })
            .catch((res) => {
              Toast("出错了");
            });
        } else {
          _this.falg = false;
          let params = {
            activity_id: _this.activity_id, // 活动ID
            val: JSON.stringify(apply_list), // 自定义表单数据
            // status: 1,// 是否打款 1否 2是
            writeoff: 1, // 是否核销 1否 2是
            // ordersn: '',// 订单编号
            // paytime: '',// 支付时间
            // transid: '',// 微信订单号
            price: _this.presentPrice, // 单价
            num: 1, // 数量
            openid: _this.openid,
            staff_id: _this.staff_id,
            // id: _this.item.id,// 修改的时候需要传
            // apply_list: apply_list
          };
          _this.$request
            .getKJZForder(params)
            .then((res) => {
              console.log("====getKJZForder======", res);
              if (res.ret == 400) {
                Dialog({ message: res.msg });
                return;
              } else if (res.ret == 200) {
                console.log(_this.presentPrice, '_this.presentPrice');
                if (_this.presentPrice == 0) {
                  Toast.success("支付成功");
                  setTimeout(function () {
                    // _this.$router.push(
                    //   `/caseShow/${_this.item.model}/ActivityShow/${_this.activity_id}`
                    // );
                    _this.$router.go(-1);
                  }, 1500);
                } else {
                  let weixinParams = {
                    appId: res.data.appId, // 公众号appId，由商户传入
                    timeStamp: res.data.timeStamp, // 时间戳
                    nonceStr: res.data.nonceStr, // 随机串
                    package: res.data.package,
                    signType: res.data.signType, // 微信签名方式
                    paySign: res.data.paySign, // 微信签名
                  };
                  WeixinJSBridge.invoke(
                    "getBrandWCPayRequest",
                    weixinParams,
                    function (res) {
                      // Toast(res.err_msg)
                      if (res.err_msg == "get_brand_wcpay_request:ok") {
                        _this.falg = true;
                        Toast("支付成功!");
                        setTimeout(function () {
                          // _this.$router.push(
                          //   `/caseShow/${_this.item.model}/ActivityShow/${_this.activity_id}`
                          // );
                          _this.$router.go(-1);
                        }, 1500);
                        // WeixinJSBridge.call('closeWindow');
                      } else if (
                        res.err_msg == "get_brand_wcpay_request:cancel"
                      ) {
                        _this.falg = true;
                        Toast("取消支付!");
                        // WeixinJSBridge.call('closeWindow');
                      } else {
                        _this.falg = true;
                        Toast("支付失败!");
                      }
                      _this.$router.go(-1);
                      // WeixinJSBridge.call('closeWindow');
                    }
                  );
                }
              }
            })
            .catch((res) => {
              Toast("出错了");
            });
        }
      }
    },
    activitySave(apply_list) {
      const _this = this;
      let params = {
        openid: _this.openid,
        id: _this.item.id,
        apply_list: apply_list,
      };
      console.log("params", params);
      this.$request
        .activitySave(params)
        .then((res) => {
          if (res.ret == 200) {
            Toast("操作成功");
            setTimeout(function () {
              _this.$router.go(-1);
            }, 2000);
          }
        })
        .catch((res) => {
          Toast("出错了");
        });
    },
  },
};
</script>